/*******************************************************************************
 * Copyright (c) 2013 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/
package com.niannian.util;

import java.util.HashMap;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import cn.jpush.android.api.JPushInterface;
import com.niannian.db.DatabaseApi;
import com.niannian.db.MyDBUser;
import com.niannian.web.nnSyncApi;

public class UpdateManager {
	public static final String MESSAGE_RECEIVED_ACTION = "com.ischool.android.MESSAGE_RECEIVED_ACTION";
	public static final String NOTIFY_RECEIVED_ACTION = "com.ischool.android.NOTIFY_RECEIVED_ACTION";
	public static final String HOME_MSG_COUNT_ACTION = "com.ischool.android.MSG_COUNT_ACTION";
	public static final String VERISON_CHECK_ACTION = "com.ischool.android.VERISON_CHECK_ACTION";
	public static final int MESSAGE_RECEIVED_PRIORITY_CHAT = 400;
	public static final int MESSAGE_RECEIVED_PRIORITY_MSG = 300;
	public static final int MESSAGE_RECEIVED_PRIORITY_MAIN = 200;

	public static final String NOTIF_TYPE_CHAT = "chat";
	public static final String NOTIF_TYPE_NOT_CHAT = "notchat";
	public static final String NOTIF_TYPE_SYS = "sys";
	public static final String NOTIF_TYPE_BE_FRIEND = "befriend";
	public static final String NOTIF_TYPE_ADD_FRIEND = "addfriend";
	public static final String NOTIF_TYPE_BE_FANS = "befans";
	public static final String NOTIF_TYPE_TWITTER = "twittercomment";
	public static final String[] relationType = new String[] { "befriend",
			"addfriend", "befans" };
	public static final String[] twitterType = new String[] { "twittercomment" };
	public static final String[] sysType = new String[] { "sys" };
	// public static final String MESSAGE_RECEIVED_ACTION
	private MyDBUser user = null;
	private Context cont = null;
	private DatabaseApi databaseapi = null;

	private UpdateManager(MyDBUser user, Context cont) {
		this.user = user;
		this.cont = cont;
		 //JPushInterface.setAliasAndTags(cont, user.getPushkey(), null);
		databaseapi = DatabaseApi.getDataBaseApi(cont);
	}

	public static UpdateManager cur = null;

	public static UpdateManager getUpdateManager() {
		return cur;
	}

	public static UpdateManager newUpdateManager(MyDBUser user, Context cont) {
		cur = new UpdateManager(user, cont);
		return cur;
	}

	/**
	 * 处理监听服务获取到的“纸条”msg消息
	 * */
	public void handleMsg(String data) {
		JSONObject extrasJson = null;
		try {
			extrasJson = new JSONObject(data);
			String msgtype = extrasJson.getString("type");
			int dateline;
			if (NOTIF_TYPE_CHAT.equals(msgtype)) {

				JSONObject notify = extrasJson.getJSONObject("notify");
				/* 这里应该保存notification，并在intent中加入type，targetid，两个参数 */
				databaseapi.saveReceivedChatMsg(user.id, notify);
				int targetid = notify.getInt("fromuid");
				String targetname = notify.getString("fromuname");
				String msg = notify.getString("msg");
				dateline = notify.getInt("dateline");

				databaseapi.addChatNotification(user.id, targetid, targetname,
						1, msg, dateline);
				Intent cur = new Intent(MESSAGE_RECEIVED_ACTION);
				cur.putExtra("type", msgtype);
				cur.putExtra("targetid", targetid);
				cur.putExtra("msg", msg);
				cur.putExtra("fromuname", targetname);
				cont.sendOrderedBroadcast(cur, null);
				// cont.sendBroadcast(new Intent(MESSAGE_RECEIVED_ACTION));
			} else {
				JSONObject notify = extrasJson.getJSONObject("notify");
				databaseapi.saveNotifyDetail(user.id, notify);
				int targetid = notify.getInt("fromuid");
				String targetname = notify.getString("fromuname");
				String msg = notify.getString("msg");
				dateline = notify.getInt("dateline");
				databaseapi.addSysNotification(user.id, targetname, msgtype, 1,
						msg, dateline);
				Intent cur = new Intent(NOTIFY_RECEIVED_ACTION);
				cur.putExtra("type", msgtype);
				cur.putExtra("targetid", targetid);
				cont.sendOrderedBroadcast(cur, null);
			}
			CheckReceived received = new CheckReceived();
			Map<String, Object> params = new HashMap<String, Object>();
			if (NOTIF_TYPE_CHAT.equals(msgtype)) {
				params.put("msgdateline", dateline);
			} else {
				params.put("notifydateline", dateline);
			}
			received.init(params);
			received.execute();
		} catch (JSONException e) {
			Log.e("Unexpected: jpush received extras is not a valid json",
					e.toString());
		}

	}

	public void checkAllMessage() {
		Map<String, Integer> map = databaseapi.checkNotifyLast(user.id);
		CheckReceived received = new CheckReceived();
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("msgdateline", map.get("chat"));
		params.put("notifydateline", map.get("sys"));
		received.init(params);
		received.execute();
	}

	class CheckReceived extends AsyncHandle {
		public void handleData(JSONObject json, Map<String, Object> parameters)
				throws JSONException {
			if (json.getInt("code") == 1) {
				int msgdateline = 0, notifydateline = 0;
				if (json.has("notifylist")) {
					JSONArray notifylist = json.getJSONArray("notifylist");
					if (notifylist.length() != 0) {
						for (int j = 0; j < notifylist.length(); j++) {
							JSONObject one = notifylist.getJSONObject(j);
							if (one.has("notifylist")) {
								JSONArray curlist = one
										.getJSONArray("notifylist");
								if (curlist.length() > 0) {
									int newNum = one.getInt("num");
									String type = one.getString("type");
									JSONObject last = curlist
											.getJSONObject(curlist.length() - 1);
									notifydateline = last.getInt("dateline") > notifydateline ? last
											.getInt("dateline")
											: notifydateline;
									databaseapi.addSysNotification(user.id,
											last.getString("fromuname"), type,
											newNum, last.getString("msg"),
											last.getInt("dateline"));
									databaseapi.saveNotifyDetail(user.id,
											curlist);
									Intent cur = new Intent(
											NOTIFY_RECEIVED_ACTION);
									cur.putExtra("type", type);
									cur.putExtra("targetid", 0);
									cont.sendOrderedBroadcast(cur, null);
								}
							}
						}
					}
				}
				if (json.has("msglist")) {
					JSONArray msglist = json.getJSONArray("msglist");
					if (msglist.length() != 0) {
						for (int j = 0; j < msglist.length(); j++) {
							JSONObject one = msglist.getJSONObject(j);
							if (one.has("msglist")) {
								JSONArray curlist = one.getJSONArray("msglist");
								if (curlist.length() > 0) {
									int newNum = one.getInt("num");
									int fromuid = one.getInt("fromuid");
									JSONObject last = curlist
											.getJSONObject(curlist.length() - 1);
									msgdateline = last.getInt("dateline") > msgdateline ? last
											.getInt("dateline") : msgdateline;
									databaseapi.addChatNotification(user.id,
											fromuid,
											last.getString("fromuname"),
											newNum, last.getString("msg"),
											last.getInt("dateline"));
									databaseapi.saveReceivedChatMsg(user.id,
											curlist);
									Intent cur = new Intent(
											MESSAGE_RECEIVED_ACTION);
									cur.putExtra("type", NOTIF_TYPE_CHAT);
									cur.putExtra("targetid", NOTIF_TYPE_CHAT);
									cont.sendOrderedBroadcast(cur, null);
								}
							}
						}
					}
				}
				if (msgdateline != 0 || notifydateline != 0) {
					parameters.clear();
					parameters.put("msgdateline", msgdateline);
					parameters.put("notifydateline", notifydateline);
					execute();
				}
			}
		}

		@Override
		protected String runTask(Map<String, Object> parameters) {
			Integer msgdateline = (Integer) parameters.get("msgdateline");
			Integer notifydateline = (Integer) parameters.get("notifydateline");
			return "";
			/*return nnSyncApi.reportReceived(msgdateline == null ? ErrorCode.OK
					: msgdateline, notifydateline == null ? 0 : notifydateline);*/
		}

	}

	/** 获取各种提醒 */
	public void handleNotification(String data) {

	}

	/**
	 * 向服务器拉取更新内容。该操作，适用于重登陆，注册后，网络断开后重连接等，初次和服务器取得联系时，对所有 更新的查询。
	 */
	public void checkUpdate() {

	}

}
